package com.alibaba.org.service.impl;

import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.basic.util.Md5Utils;
import com.alibaba.basic.util.StrUtils;
import com.alibaba.org.domain.Emp;
import com.alibaba.org.mapper.EmpMapper;
import com.alibaba.org.service.EmpService;
import com.alibaba.user.domain.Logininfo;
import com.alibaba.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EmpServiceImpl extends BaseServiceImpl<Emp> implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    @Transactional
    public void add(Emp emp) {
        // 生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(emp.getPassword() + salt);
        emp.setSalt(salt);
        emp.setPassword(md5Pwd);

        // 保存logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(emp, logininfo);
        logininfo.setType(0);
        logininfo.setDisable(true);
        logininfoMapper.add(logininfo);
        emp.setLogininfo_id(logininfo.getId());
        empMapper.add(emp);
        Long id = emp.getId();
        if (emp.getRole_id() != null) {
            empMapper.addEmpRole(emp);
        }
    }

    @Override
    @Transactional
    public void remove(Long id) {
        empMapper.removeEmpRoleByEmpId(id);

        Emp user = empMapper.findById(id);
        logininfoMapper.remove(user.getLogininfo_id());
        super.remove(id);
    }

    @Override
    @Transactional
    public void update(Emp emp) {
        empMapper.removeEmpRoleByEmpId(emp.getId());
        if (emp.getRole_id() != null) {
            empMapper.addEmpRole(emp);
        }
        String salt = StrUtils.getComplexRandomString(32);
        String md5 = Md5Utils.encrypByMd5(emp.getPassword() + salt);
        emp.setSalt(salt);
        emp.setPassword(md5);
        super.update(emp);
        // 先获取老的对象
        Long logininfoId = empMapper.findById(emp.getId()).getLogininfo_id();

        // 再根据logininfoId查询
        Logininfo logininfo = logininfoMapper.findById(logininfoId);
        BeanUtils.copyProperties(emp, logininfo);
        logininfoMapper.update(logininfo);
    }
}
